package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.CourseTeacherDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.CourseTeacherService;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mr.M
 * @version 1.0
 * @description 课程计划service接口实现类
 * @date 2022/9/9 11:14
 */
@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private TeachplanService teachplanService;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;
    @Autowired
    private CourseTeacherService courseTeacherService;

    /**
     * 展示师资信息
     * @param
     */
    @Override
    public List<CourseTeacherDto> list(Long companyId,Long courseId) {
        // 1. 校验参数
        if (courseId == null) {
            throw new XueChengPlusException("课程ID不能为空");
        }

        // 2. 基于PO类（CourseTeacher）查询数据库（对应course_teacher表）
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId, courseId); // 仅按课程ID查询
        List<CourseTeacher> teacherPoList = courseTeacherMapper.selectList(queryWrapper);

        // 3. 转换为DTO（PO -> DTO），并补充companyId
        return teacherPoList.stream().map(po -> {
            CourseTeacherDto dto = new CourseTeacherDto();
            BeanUtils.copyProperties(po, dto); // 复制PO的字段（id、courseId等）
            dto.setCompanyId(companyId); // 补充DTO的业务字段（非数据库字段）
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 更新师资信息
     */
    @Override
    @Transactional
    public void update(CourseTeacherDto courseTeacherDto){
        // 1. 校验参数
        if (courseTeacherDto.getCourseId() == null) {
            throw new XueChengPlusException("课程ID不能为空");
        }
        if (org.apache.commons.lang3.StringUtils.isBlank(courseTeacherDto.getTeacherName())) {
            throw new XueChengPlusException("教师姓名不能为空");
        }

        // 2. DTO转换为PO（仅保留数据库表对应的字段）
        CourseTeacher teacherPo = new CourseTeacher();
        BeanUtils.copyProperties(courseTeacherDto, teacherPo);

        // 3. 区分新增和更新
        if (teacherPo.getId() == null) {
            // 3.1 新增：设置创建时间，执行插入
            teacherPo.setCreateDate(LocalDateTime.now());
            courseTeacherMapper.insert(teacherPo);
        } else {
            // 3.2 更新：按ID更新，校验是否存在
            int rows = courseTeacherMapper.updateById(teacherPo);
            if (rows == 0) {
                throw new XueChengPlusException("教师信息不存在，更新失败");
            }
        }
    }

    /**
     * 删除教师信息
     * @param courseId
     * @param teacherId
     */
    @Override
    @Transactional
    public void delete(Long courseId, Long teacherId) {
        // 1.合法性检验
        if(courseId == null || courseId <= 0L){
            XueChengPlusException.cast("课程不存在或参数非法");
        }
        if(teacherId == null || teacherId <= 0L){
            XueChengPlusException.cast("教师信息不存在或参数非法");
        }
        // 2.查看是否为本机构的课程
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        Long companyId = courseBase.getCompanyId();
        if(companyId != 1232141425L){
            XueChengPlusException.cast("不能删除其他机构的课程教师");
        }
        // 2.根据课程id和教师id删除课程对应的教师信息
        LambdaQueryWrapper<CourseTeacher> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseTeacher::getCourseId,courseId)
                .eq(CourseTeacher::getId,teacherId);
        int result = courseTeacherMapper.delete(lambdaQueryWrapper);
        if(result <= 0){
            XueChengPlusException.cast("删除课程教师失败");
        }
    }

    /**
     * 删除课程
     * @param courseId
     */
    @Override
    @Transactional
    public void deleteCourse(Long courseId,Long companyId) {
        // 合法性校验
        if(courseId == null || courseId <= 0){
            XueChengPlusException.cast("课程不存在或参数非法");
        }
        //只能删除本机构的课程
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(!companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("不能删除其他机构的课程");
        }
        //课程的审核状态为未提交时才可删除
        if(!courseBase.getAuditStatus().equals("202002")){
            XueChengPlusException.cast("课程的审核状态为已提交，不可删除");
        }

        //删除课程需要删除课程的基本信息、营销信息、课程计划、课程计划视频信息、教师信息
        //删除教师信息
        List<CourseTeacherDto> courseTeacherDtos = courseTeacherService.list(companyId,courseId);
        List<Long> teacherIds = courseTeacherDtos.stream()
                .map(CourseTeacherDto::getId)
                .collect(Collectors.toList());
        // 仅当ID列表不为空时执行删除
        if (!teacherIds.isEmpty()) {
            int result = courseTeacherMapper.deleteBatchIds(teacherIds);
            if (result <= 0) {
                XueChengPlusException.cast("删除教师信息失败");
            }
        }

        //删除课程计划信息及视频信息
        List<TeachplanDto> teachplanDtos = teachplanService.findTeachplanTree(courseId);
        for (TeachplanDto teachplanDto : teachplanDtos) {
            for (TeachplanDto teachPlanTreeNode : teachplanDto.getTeachPlanTreeNodes()) {
                TeachplanMedia teachplanMedia = teachPlanTreeNode.getTeachplanMedia();
                //删除视频信息
                if (teachplanMedia != null) { // 添加空检查
                    teachplanMediaMapper.deleteById(teachplanMedia.getId());
                }
                //删除课程计划信息
                teachplanService.deleteTeachplan(teachPlanTreeNode.getId());
            }
            teachplanService.deleteTeachplan(teachplanDto.getId());
        }

        //删除课程营销信息
        courseMarketMapper.deleteById(courseId);
        //删除课程基本信息
        courseBaseMapper.deleteById(courseId);
    }
}